package top.xcxdl.rural.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.StringUtils;
import top.xcxdl.rural.entity.BackAuthGroupRule;
import top.xcxdl.rural.entity.BackAuthRule;
import top.xcxdl.rural.mapper.BackAuthRuleMapper;
import top.xcxdl.rural.service.IBackAuthRuleService;
import org.springframework.stereotype.Service;
import top.xcxdl.rural.utils.JWTUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Ding
 * @since 2022-01-27
 */
@Log4j2
@Service
public class BackAuthRuleServiceImpl extends ServiceImpl<BackAuthRuleMapper, BackAuthRule> implements IBackAuthRuleService {

    @Resource
    private BackAuthRuleMapper mapper;

    private final static String SUPER_ADMIN = "SUPER_ADMIN";
    private final static String ADMIN = "ADMIN";

    @Override
    public List<BackAuthRule> getAllRules(String ruleIds, String roleCode) {
        //根据已有rules获取所拥有的权限主键索引ids
        List<BackAuthRule> rules = new ArrayList<>();
        //获取rules
        if (SUPER_ADMIN.equals(roleCode)) {
            //最高权限，获取所有rules
            rules = mapper.getAllRules(null,null);
            toDoRules(rules);
        } else if (ADMIN.equals(roleCode)) {
            //普通权限，根据拥有权限获取rules
            if (!StringUtils.isEmpty(ruleIds)) {
                //将"1,2,3"的字符串id集转换成字符串数组->再转为集合->"[1,2,3]"
                List<String> idsList = Arrays.asList(ruleIds.split(","));
                rules = mapper.getAllRules(ruleIds,idsList);
                toDoRules(rules);
            }
        }
        return rules;
    }

    public void toDoRules(List<BackAuthRule> list) {

        for (BackAuthRule rule : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("title", rule.getTitle());
            jsonObject.put("icon", rule.getIcon());
            if("/".equals(rule.getPath())){
                jsonObject.put("breadcrumbHidden", true);
            }
            if("/index".equals(rule.getPath())){
                jsonObject.put("noClosable", true);
            }
            rule.setMeta(jsonObject);
            if (rule.getChildren() != null) {
                toDoRules(rule.getChildren());
            }
        }
    }

    @Override
    public boolean checkIsForbidden(List<Integer> ruleIds) {
        QueryWrapper<BackAuthRule> wrapper = new QueryWrapper<>();
        wrapper.in("r_id", ruleIds)
                .eq("`disabled`", 1);
        return mapper.selectCount(wrapper) > 0;
    }

    @Override
    public int doEdit(BackAuthRule bean) {
        bean.setUpdateTime(Long.valueOf(String.valueOf(System.currentTimeMillis() / 1000)));
        if (bean.getRuleId() == null) {
            //添加
            bean.setCreateTime(Long.valueOf(String.valueOf(System.currentTimeMillis() / 1000)));
            return mapper.insert(bean);
        } else {
            //编辑
            QueryWrapper<BackAuthRule> wrapper = new QueryWrapper<>();
            wrapper.eq("r_id", bean.getRuleId());
            return mapper.update(bean, wrapper) + 1;
        }
    }

    @Override
    public int doDeleteBy(List<Integer> ids) {
        int real = 0;
        for (Integer id : ids) {
            //获取所有子节点id
            List<Integer> allIds = mapper.getDelIdIgnoreThisId(id);
            //把本体也添加进去
            allIds.add(id);
            //再联系库，把这些ID删除，并返回删除数量
            real += mapper.menuItemDel(allIds);
        }
        if(real > 0 ){
            log.info("管理员{}（ID为{}）：删除了{}个菜单", JWTUtils.getAuthorName(), JWTUtils.getAuthorId(),ids.size());
        }
        //往回返回
        return real;
    }

    @Override
    public List<Integer> getAllTopRules(Integer ruleId) {
        return mapper.getAllTopRules(ruleId);
    }

    @Override
    public List<BackAuthRule> getAllRulesNoTree(List<BackAuthGroupRule> groupRules, String roleCode) {
        //根据已有rules获取所拥有的权限主键索引ids
        List<BackAuthRule> rules = new ArrayList<>();
        QueryWrapper<BackAuthRule> wrapper = new QueryWrapper<>();
        //获取rules
        if (SUPER_ADMIN.equals(roleCode)) {
            //最高权限，获取所有rules
            rules = mapper.selectList(wrapper);
        } else if (ADMIN.equals(roleCode)) {
            List<Integer> ids = new ArrayList<>();
            for (BackAuthGroupRule g : groupRules) {
                ids.add(g.getRuleId());
            }
            wrapper.in("r_id", ids);
            rules = mapper.selectList(wrapper);
        }
        return rules;
    }

    @Override
    public String isRequestExist(Integer groupId, String requestUri) {
        return baseMapper.isRequestExist(groupId,requestUri);
    }

}
